package com.glaive;

import cn.hutool.core.io.FileUtil;
import com.glaive.utils.ChineseNum2int;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BookTxtHandleCmd {
    static String filePath = System.getProperty("user.dir") + "\\首席高参20200202修正.txt";

    static List<String> strList = new LinkedList<>();

    public static void main(String[] args) throws Exception {
        readLine();
    }

    public static void readLine2() throws Exception {
        ArrayList<String> readUtf8Lines = FileUtil.readUtf8Lines(filePath, new ArrayList<>());
        for (int i = 0; i < readUtf8Lines.size(); i++) {
            String ss = readUtf8Lines.get(i);
            System.out.println(ss);
        }
    }

    /**
     *
     */
    public static void readLine() throws Exception {
        //正则说明：
        // 1. 三位数加空格开头
        Pattern pattern = Pattern.compile(
                "(第(.*?)卷)(.*?)(第(.*?)节)(.*)"
        );

        Files
                .lines(Paths.get(filePath))
                .map(s -> {
                    Matcher m = pattern.matcher(s);
                    if (m.find()) {
                        int xx = ChineseNum2int.chineseNumToArabicNum(m.group(2));
                        int xx2 = ChineseNum2int.chineseNumToArabicNum(m.group(5));
                        String volume = "第" + xx + "卷 ";
                        volume = volumeHandle(volume, m.group(3));
                        String section = " 第" + xx2 + "节 ";
                        String indexSection = section + m.group(6);
                        boolean isRep = indexIsRepeat(volume, section);

                        String index = volume + indexSection;
                        if (isRep) {
                            return "";
                        } else {
                            return index;
                        }
                    } else
                        return s;
//                        return "";
                })
                .distinct()
                .forEach(s -> {
                    System.out.println(s + "\n");
                });
    }

    static String volumeSection = "";

    /**
     * 索引 去重
     *
     * @param volume
     * @param section
     * @return
     */
    private static boolean indexIsRepeat(String volume, String section) {
        if (volumeSection.equals(volume + section)) {
            return true;
        } else {
            volumeSection = volume + section;
            return false;
        }

    }

    static String volumeTmp = "";

    /**
     * 卷的索引处理：只有第一卷的首次出现 都会显示卷的标题，其他省略
     */
    private static String volumeHandle(String volume, String volumeValue) {
        if (!volumeTmp.equals(volume + volumeValue)) {
            volumeTmp = volume + volumeValue;
            return volumeTmp;
        } else {
            return volume;
        }
    }
}